use serde::{Serialize, Deserialize};
use crate::util::log_helper::push_error;
use crate::util::path_helper::{get_target_app_file_url_by, get_target_app_file_url_from_vec};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all="camelCase")]
pub struct AppFiles {
  pub css_file: String,
  pub js_file: String,
}

impl AppFiles {
  pub fn get_is_same(&self, other: &Self) -> bool {
    self.css_file == other.css_file && self.js_file == other.js_file
  }

  pub fn from_html(html: &str) -> Option<Self> {
    let dom_result = tl::parse(html, tl::ParserOptions::default());
    if dom_result.is_err() {
      push_error(format!("parse html error: {}, html: {}", dom_result.err().unwrap(), html));
      return None;
    }
    let mut dom = dom_result.unwrap();
    let script_src_vec = get_target_app_file_url_by(&mut dom, html, "script", "src");
    let target_script_src = get_target_app_file_url_from_vec(&script_src_vec, "js");
    let style_src_vec = get_target_app_file_url_by(&mut dom, html, "link", "href");
    let target_style_src = get_target_app_file_url_from_vec(&style_src_vec, "css");
    return Some(AppFiles { 
      css_file: target_style_src.clone(), 
      js_file: target_script_src.clone() 
    });
  }
}
